﻿
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>仓库与库位管理</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>

    <style>
        .btn-group {
            display: flex;
            gap: 8px;
        }

        .saveBlock {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
            background-color: #fff;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 999;
            margin: 0;
        }

        .font-heiti {
            font-family: "黑体", sans-serif;
        }

        .basicInfo, .locationInfo {
            width: 82%;
            background-color: #fff;
            padding: 20px;
            margin: 20px 0 0 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
        }

        .locationInfo {
            padding-bottom: 80px;
        }

        .titleH {
            margin: 0 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #303133;
            font-weight: 600;
            width: 100%;
        }

        .orderTable {
            width: 100%;
            border-spacing: 0 20px;
        }

            .orderTable td {
                vertical-align: top;
                padding: 8px 0;
                text-align: left;
                color: #303133;
            }

                .orderTable td:first-child {
                    width: 12%;
                    text-align: right !important;
                    padding-right: 15px;
                    color: #303133 !important;
                    font-weight: normal;
                    white-space: nowrap;
                }

        .imp {
            color: red;
        }

        .location-table .el-table__column--selection,
        .location-table .el-table__column--action {
            width: 80px;
        }

        .location-btn-group {
            display: flex;
            gap: 8px;
            margin: 10px 0 20px;
        }

        .pagination {
            display: flex;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .el-input, .el-textarea {
            margin-bottom: 5px;
        }

        .drawer-content {
            padding: 20px;
        }

        .form-row {
            display: flex;
            margin-bottom: 16px;
        }

        .form-item {
            width: 50%;
            margin-right: 20px;
        }

        .form-footer {
            display: flex;
            justify-content: flex-end;
            margin-top: 24px;
        }

            .form-footer .el-button {
                margin-left: 12px;
            }

        /* 表格样式调整：无表格线 + 一灰一白行 */
        .el-table {
            border: none !important;
        }

            /* 去除表格所有边框线 */
            .el-table::before,
            .el-table::after,
            .el-table--border::after,
            .el-table--group::after,
            .el-table__inner-wrapper::before,
            .el-table__inner-wrapper::after {
                background-color: transparent !important;
            }

            .el-table th,
            .el-table td {
                border-right: none !important;
                border-bottom: none !important;
            }

                /* 表头背景色 */
                .el-table th.el-table__cell {
                    background-color: #f5f7fa !important;
                }

        /* 表格行一灰一白交替 */
        .el-table__body tr:nth-child(odd) td.el-table__cell {
            background-color: #f9fafc !important;
        }

        .el-table__body tr:nth-child(even) td.el-table__cell {
            background-color: #ffffff !important;
        }

        /* 鼠标悬停行样式 */
        .el-table__body tr:hover td.el-table__cell {
            background-color: #f0f7ff !important;
        }

        /* 选中行样式 */
        .el-table__body tr.current-row td.el-table__cell {
            background-color: #e6f7ff !important;
        }

        /* 选中人员样式 */
        .person-selected {
            background-color: #e6f7ff !important;
        }

        #confirm-manager-btn {
            position: relative;
            z-index: 9999; /* 确保按钮在最上层 */
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 一、仓库基础信息模块 -->
        <div class="basicInfo">
            <h2 class="titleH">基础信息</h2>
            <table class="orderTable">
                <tbody>
                    <!-- 第一行：仓库编号 + 默认仓库 + 仓库名称 -->
                    <tr>
                        <td><span class="imp font-heiti"></span> 仓库编号</td>
                        <td>
                            <el-input v-model="warehouse.warehouseCode" style="width:80%" readonly placeholder="自动获取系统编号"></el-input>
                        </td>
                        <td>
                            <el-checkbox v-model="warehouse.isDefaultWarehouse" label="默认仓库"></el-checkbox>
                        </td>
                        <td><span class="imp font-heiti"></span> 仓库名称</td>
                        <td>
                            <el-input v-model="warehouse.warehouseName" style="width:80%" placeholder="请输入"></el-input>
                        </td>
                    </tr>

                    <!-- 第二行：仓库容量/m³ + 库管部门 -->
                    <tr>
                        <td class="font-heiti">仓库容量/m³</td>
                        <td>
                            <el-input v-model.number="warehouse.warehouseCapacity" style="width:80%" placeholder="请输入"></el-input>
                        </td>
                        <td></td>
                        <td class="font-heiti">库管部门</td>
                        <td>
                            <el-input v-model="warehouse.ManageOrgId" style="width:80%" placeholder="请输入" readonly />
                            <el-button type="text" v-on:click="openOrgSelect">...</el-button>
                        </td>
                    </tr>

                    <!-- 第三行：仓库主管 + 联系电话 -->
                    <tr>
                        <td class="font-heiti">仓库主管</td>
                        <td>
                            <el-input v-model="warehouse.ManageId" style="width:80%" v-on:click="openManagerSelect" placeholder="请选择" readonly />
                            <el-button type="text" v-on:click="openManagerSelect">...</el-button>
                        </td>
                        <td></td>
                        <td class="font-heiti">联系电话</td>
                        <td>
                            <el-input v-model="warehouse.UsersHoneUmber" style="width:80%" readonly />
                        </td>
                    </tr>

                    <!-- 第四行：仓库地址 -->
                    <tr>
                        <td class="font-heiti">仓库地址</td>
                        <td colspan="4">
                            <el-input v-model="warehouse.warehouseAddress" style="width:95%" placeholder="请输入详细地址"></el-input>
                        </td>
                    </tr>

                    <!-- 第五行：排序 + 仓库状态 -->
                    <tr>
                        <td class="font-heiti">排序</td>
                        <td>
                            <el-input v-model.number="warehouse.sortOrder" style="width:80%" placeholder="请输入"></el-input>
                        </td>
                        <td></td>
                        <td class="font-heiti">仓库状态</td>
                        <td colspan="2">
                            <el-radio-group v-model="warehouse.warehouseStatus" v-on:change="handleStatusChange">
                                <el-radio label="启用" border>启用</el-radio>
                                <el-radio label="停用" border>停用</el-radio>
                            </el-radio-group>
                        </td>
                    </tr>

                    <!-- 第六行：仓库锁定（根据状态显示/隐藏） -->
                    <tr v-if="warehouse.warehouseStatus === '启用'">
                        <td class="font-heiti">仓库锁定</td>
                        <td colspan="4">
                            <el-switch v-model="warehouse.warehouseLocked"
                                       active-value="Y"
                                       inactive-value="N"></el-switch>
                        </td>
                    </tr>

                    <!-- 第七行：备注（根据状态调整位置） -->
                    <tr>
                        <td class="font-heiti">备注</td>
                        <td colspan="4">
                            <el-input v-model="warehouse.remarks" type="textarea" rows="4" style="width:95%" placeholder="请输入"></el-input>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 二、库位信息模块（核心：分页多选） -->
        <div class="locationInfo">
            <h2 class="titleH">库位信息</h2>
            <div class="location-btn-group">
                <el-button type="primary" v-on:click="openAddLocationDialog" :disabled="!isWarehouseSaved">新增</el-button>
                <el-button type="danger" v-on:click="batchDeleteLocation" :disabled="selectedLocations.length === 0">批量删除</el-button>
                <el-button type="info" v-on:click="importLocation">导入</el-button>
                <el-button type="success" v-on:click="exportLocation">导出</el-button>
            </div>

            <!-- 库位表格 -->
            <el-table :data="pagedLocationList"
                      header-align="center"
                      ref="multipleTable"
                      v-on:selection-change="handleSelectionChange"
                      style="width: 100%;">
                <!-- 多选框列 -->
                <el-table-column type="selection"
                                 width="60"
                                 align="center"></el-table-column>

                <!-- 序号列 -->
                <el-table-column type="index"
                                 label="序号"
                                 width="60"
                                 align="center"
                                 :index-method="(index) => (currentPage - 1) * pageSize + index + 1"></el-table-column>

                <el-table-column prop="storageLocationCode" label="库位编号" width="120" align="center"></el-table-column>
                <el-table-column prop="storageLocationName" label="库位名称" width="120" align="center"></el-table-column>
                <el-table-column prop="storageLocationCapacity" label="库位容量/m³" width="120" align="center"></el-table-column>
                <el-table-column prop="warehouseManagerName" label="库位主管" width="120" align="center"></el-table-column>

                <el-table-column label="库位状态" width="100" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.storageLocationStatus === 1 ? 'success' : 'danger'">
                            {{ scope.row.storageLocationStatus == 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sortOrder" label="排序" width="80" align="center"></el-table-column>
                <el-table-column prop="remarks" label="备注" align="center"></el-table-column>
                <el-table-column label="操作" width="120" align="center">
                    <template #default="scope">
                        <el-button type="text" v-on:click="openEditLocationDialog(scope.row)">编辑</el-button>
                        <el-button type="text" style="color: #ff4d4f" v-on:click="deleteLocation(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination">
                <el-pagination v-model:current-page="currentPage"
                               v-model:page-size="pageSize"
                               :total="total"
                               layout="prev, pager, next, ->, jumper, ->, total, sizes"
                               :page-sizes="[10, 20, 50, 100]"
                               v-on:size-change="handleSizeChange"
                               v-on:current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 三、保存按钮区 -->
        <div class="saveBlock">
            <div class="btn-group">
                <el-button v-on:click="closePage">关闭</el-button>
                <el-button type="primary" v-on:click="saveAndAdd">保存并新增</el-button>
                <el-button type="primary" v-on:click="saveData">保存</el-button>
            </div>
        </div>

        <!-- 四、编辑弹窗 -->
        <el-dialog v-model="locationDialogVisible" :title="locationDialogTitle">
            <el-form :model="currentLocation" label-width="120px">
                <el-form-item label="库位编号" required>
                    <el-input v-model="currentLocation.storageLocationCode" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="库位名称" required>
                    <el-input v-model="currentLocation.storageLocationName" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="库位容量/m³" required>
                    <el-input v-model.number="currentLocation.storageLocationCapacity" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="库位主管" required>
                    <el-input v-model="currentLocation.managerName" style="width: 80%" placeholder="请选择" readonly />
                    <el-button type="text" v-on:click="openLocationManagerSelect">...</el-button>
                </el-form-item>
                <el-form-item label="库位状态" required>
                    <el-radio-group v-model="currentLocation.storageLocationStatus">
                        <el-radio label="1">启用</el-radio>
                        <el-radio label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="排序" required>
                    <el-input v-model.number="currentLocation.sortOrder" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="currentLocation.remarks" style="width: 80%"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button v-on:click="locationDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="saveLocation">确定</el-button>
            </template>
        </el-dialog>

        <!-- 五、新增库位抽屉 -->
        <el-drawer v-model="addDrawerVisible"
                   title="新增库位"
                   direction="rtl"
                   size="50%">
            <div class="drawer-content">
                <el-form :model="newLocationForm" label-width="100px">
                    <div class="form-row">
                        <el-form-item label="库位编号" class="form-item">
                            <el-input v-model="newLocationForm.storageLocationCode" placeholder="自动获取系统编号" readonly />
                        </el-form-item>
                        <el-form-item label="库位名称" class="form-item">
                            <el-input v-model="newLocationForm.storageLocationName" placeholder="请输入" />
                        </el-form-item>
                    </div>
                    <div class="form-row">
                        <el-form-item label="库位容量/m³" class="form-item">
                            <el-input v-model.number="newLocationForm.storageLocationCapacity" placeholder="请输入" />
                        </el-form-item>
                        <el-form-item label="库位主管" class="form-item">
                            <el-input v-model="newLocationForm.managerName"
                                      placeholder="请选择"
                                      readonly
                                      v-on:click="openNewLocationManagerSelect" />
                            <el-button type="text" v-on:click="openNewLocationManagerSelect"></el-button>

                        </el-form-item>
                    </div>
                    <div class="form-row">
                        <el-form-item label="库位状态" class="form-item">
                            <el-radio-group v-model="newLocationForm.storageLocationStatus">
                                <el-radio label="1">启用</el-radio>
                                <el-radio label="0">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="排序" class="form-item">
                            <el-input v-model.number="newLocationForm.sortOrder" placeholder="请输入" />
                        </el-form-item>
                    </div>
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="newLocationForm.remarks" placeholder="请输入" rows="4" />
                    </el-form-item>
                    <div class="form-footer">
                        <el-button v-on:click="addDrawerVisible = false">取消</el-button>
                        <el-button type="primary" v-on:click="saveNewLocation" native-type="button">保存</el-button>
                    </div>
                </el-form>
            </div>
        </el-drawer>

        <!-- 主管选择弹窗（合并为一个，通过标题区分） -->
        <el-dialog v-model="managerDialogVisible" :title="managerDialogTitle" width="500px">
            <div class="search-box">
                <el-input v-model="managerSearchKeyword"
                          placeholder="请搜索人员姓名或部门"
                          prefix-icon="Search"
                          v-on:input="filterManagers"
                          clearable />
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoadingManagers" style="text-align: center; padding: 50px 0;">
                <el-loading-spinner></el-loading-spinner>
                <p style="margin-top: 10px;">加载人员列表中...</p>
            </div>

            <!-- 无数据状态 -->
            <div v-else-if="Object.keys(groupedManagers).length === 0 && !isLoadingManagers" style="text-align: center; padding: 50px 0;">
                <p>没有找到匹配的人员</p>
            </div>

            <!-- 按部门分组展示的人员列表 -->
            <div v-else class="manager-group-container" style="max-height: 400px; overflow-y: auto; padding: 10px 0;">
                <template v-for="(deptPersons, deptName) in groupedManagers" :key="deptName">
                    <div class="dept-title" style="font-weight: bold; padding: 8px 16px; background: #f5f7fa;">
                        {{ deptName }} ({{ deptPersons.length }})
                    </div>
                    <div class="person-list">
                        <div v-for="person in deptPersons"
                             :key="person.userId"
                             class="person-item"
                             :data-userid="person.userId"
                             :class="{ 'person-selected': selectedManager?.userId === person.userId }"
                             v-on:click="selectManager(person)"
                             style="padding: 10px 16px; cursor: pointer; border-bottom: 1px solid #f5f7fa;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span>{{ person.userName }}</span>
                                <el-checkbox :checked="selectedManager?.userId === person.userId"
                                             :label="person.userId"
                                             change="(checked) => { if (checked) selectManager(person); }"></el-checkbox>
                            </div>
                        </div>
                    </div>
                </template>
            </div>

            <template #footer>
                <el-button v-on:click="managerDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmManagerSelection" id="confirm-manager-btn">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, computed, nextTick, reactive } = Vue;
        const { ElMessage, ElMessageBox, ElLoading, ElDialog, ElTable, ElTableColumn, ElInput, ElButton } = ElementPlus;

        createApp({
            components: {
                ElDialog,
                ElTable,
                ElTableColumn,
                ElInput,
                ElButton
            },
            setup() {

                // 仓库基础信息
                const warehouse = ref({
                    warehouseId: '',
                    warehouseCode: '',
                    isDefaultWarehouse: false,
                    warehouseName: '',
                    warehouseCapacity: '',
                    warehouseAddress: '',
                    manageOrgId: '',
                    manageOrgName: '',
                    managerId: '',
                    managerName: '',
                    UsersHoneUmber: '',
                    sortOrder: '',
                    warehouseStatus: '启用',
                    warehouseLocked: 'N',
                    remarks: ''
                });

                // 人员选择弹窗相关（合并为一个弹窗，通过标题区分类型）
                const managerDialogVisible = ref(false); // 弹窗显隐
                const managerDialogTitle = ref('选择主管'); // 弹窗标题，用于区分是仓库主管还是库位主管
                const allManagers = ref([]);            // 所有人员列表
                const deptList = ref([{ deptName: '仓储部', users: [] }]); // 按部门分组的人员
                const selectedManager = ref(null);      // 选中的主管

                // 状态管理
                const isWarehouseSaved = ref(false); // 标记仓库是否已保存到数据库
                const tempLocationList = ref([]); // 暂存库位数据

                // 库位信息
                const locationList = ref([]);
                const selectedLocations = ref([]); // 分页多选的选中项
                const locationDialogVisible = ref(false);
                const locationDialogTitle = ref('编辑库位');
                const currentLocation = ref({
                    storageLocationId: '',
                    storageLocationCode: '',
                    storageLocationName: '',
                    storageLocationCapacity: '',
                    managerId: '',
                    managerName: '',
                    storageLocationStatus: '1',
                    sortOrder: '',
                    remarks: ''
                });

                // 分页相关
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = ref(0);
                const pagedLocationList = ref([]);

                // 新增库位抽屉相关
                const addDrawerVisible = ref(false);
                const newLocationForm = ref({
                    storageLocationCode: '',
                    storageLocationName: '',
                    storageLocationCapacity: '',
                    managerId: '',
                    managerName: '',
                    storageLocationStatus: '1',
                    sortOrder: '',
                    remarks: ''
                });

                // 搜索功能
                const searchKeyword = ref('');

                // 表格实例（用于操作多选状态）
                const multipleTable = ref(null);
                // 加载中状态
                const loading = ref(false);

                // 库位主管选择弹窗相关
                const managerSearchKeyword = ref('');
                const filteredManagers = ref([]);
                const isManagersLoaded = ref(false); // 标记人员列表是否已加载
                const isLoadingManagers = ref(false); // 人员加载中状态

                // 按部门分组的人员列表（带搜索过滤）
                const groupedManagers = computed(() => {
                    const groups = {};
                    filteredManagers.value.forEach(person => {
                        const dept = person.deptName || '仓储部';
                        if (!groups[dept]) {
                            groups[dept] = [];
                        }
                        groups[dept].push(person);
                    });
                    return groups;
                });

                // -------------------------- 状态变更处理 --------------------------
                // 仓库状态变更处理
                const handleStatusChange = (status) => {
                    // 状态变更时的逻辑处理
                    console.log('仓库状态变更为:', status);
                };

                // -------------------------- 分页多选核心逻辑 --------------------------
                // 多选选中行变化时保存选中项
                const handleSelectionChange = (val) => {
                    selectedLocations.value = val;
                };

                // 切换页码时保持选中状态
                const handleCurrentChange = async (val) => {
                    const prevSelected = [...selectedLocations.value]; // 保存当前选中项
                    currentPage.value = val;
                    updatePagedLocationList(); // 更新分页数据

                    // 重新勾选新页中已选中的项
                    if (multipleTable.value && prevSelected.length > 0) {
                        pagedLocationList.value.forEach(row => {
                            const isSelected = prevSelected.some(item =>
                                item.storageLocationCode === row.storageLocationCode
                            );
                            if (isSelected) {
                                multipleTable.value.toggleRowSelection(row, true);
                            }
                        });
                    }
                };

                // 切换页大小时清空选中（数据结构变化）
                const handleSizeChange = async (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                    selectedLocations.value = [];
                    if (multipleTable.value) {
                        multipleTable.value.clearSelection();
                    }
                    updatePagedLocationList();
                };

                // 更新分页数据
                const updatePagedLocationList = () => {
                    // 计算当前页数据
                    const startIndex = (currentPage.value - 1) * pageSize.value;
                    const endIndex = startIndex + pageSize.value;
                    pagedLocationList.value = tempLocationList.value.slice(startIndex, endIndex);
                    total.value = tempLocationList.value.length;
                };

                // -------------------------- 数据加载与业务逻辑 --------------------------
                // 页面初始化
                onMounted(async () => {
                    // 1. 自动生成仓库编号
                    const warehouseCode = await generateWarehouseCode();
                    if (warehouseCode) {
                        warehouse.value.warehouseCode = warehouseCode;
                    }

                    // 2. 初始化时不加载数据库中的库位数据，只显示暂存数据
                    tempLocationList.value = [];
                    updatePagedLocationList();
                });

                // 获取所有人员信息
                const fetchAllManagers = async () => {
                    if (isManagersLoaded.value) return;
                    try {
                        isLoadingManagers.value = true;
                        const response = await axios.get('/BiWarehouse/GetUniqueLocationManagers');
                        if (response.data.code === 200) {
                            allManagers.value = response.data.data.map(item => ({
                                userId: item.UserId?.toString() || '',
                                userName: item.LocationManagerName || '',
                                deptName: item.deptName || '仓储部',
                                phone: item.UsersHoneUmber || ''
                            }));
                            filteredManagers.value = [...allManagers.value];
                            isManagersLoaded.value = true;
                        }
                    } catch (error) {
                        ElMessage.error('获取人员列表异常：' + error.message);
                    } finally {
                        isLoadingManagers.value = false;
                    }
                };

                // 搜索过滤人员
                const filterManagers = (keyword) => {
                    if (!keyword) {
                        filteredManagers.value = [...allManagers.value];
                        return;
                    }
                    const lowerKeyword = keyword.toLowerCase();
                    filteredManagers.value = allManagers.value.filter(item =>
                        (item.userName && item.userName.toLowerCase().includes(lowerKeyword)) ||
                        (item.deptName && item.deptName.toLowerCase().includes(lowerKeyword))
                    );
                };

                // 选择主管
                const selectManager = (row) => {
                    selectedManager.value = { ...row };

                    // 同步UI高亮
                    nextTick(() => {
                        document.querySelectorAll('.person-item').forEach(item => {
                            item.classList.remove('person-selected');
                        });
                        const selectedItem = document.querySelector(`.person-item[data-userid="${row.userId}"]`);
                        if (selectedItem) {
                            selectedItem.classList.add('person-selected');
                        }
                    });
                };

                // 确认选择主管
                const confirmManagerSelection = () => {
                    if (!selectedManager.value) {
                        managerDialogVisible.value = false;
                        return;
                    }

                    // 根据弹窗标题区分是仓库主管还是库位主管
                    if (managerDialogTitle.value === '选择仓库主管') {
                        warehouse.value.managerId = selectedManager.value.userId;
                        warehouse.value.managerName = selectedManager.value.userName;
                        warehouse.value.UsersHoneUmber = selectedManager.value.phone || '';
                    } else if (addDrawerVisible.value) {
                        newLocationForm.value.managerId = selectedManager.value.userId;
                        newLocationForm.value.managerName = selectedManager.value.userName;
                    } else if (locationDialogVisible.value) {
                        currentLocation.value.managerId = selectedManager.value.userId;
                        currentLocation.value.managerName = selectedManager.value.userName;
                    }

                    managerDialogVisible.value = false;
                    selectedManager.value = null; // 重置选择
                };

                // 打开库位主管选择弹窗（编辑场景）
                const openLocationManagerSelect = async () => {
                    managerDialogTitle.value = '选择库位主管';
                    await fetchAllManagers();
                    managerDialogVisible.value = true;
                };

                // 打开库位主管选择弹窗（新增场景）
                const openNewLocationManagerSelect = async () => {
                    //managerDialogTitle.value = '选择库位主管';
                    await fetchAllManagers();
                    managerDialogVisible.value = true;
                };

                // 打开仓库主管选择弹窗
                const openManagerSelect = async () => {
                    try {
                        // 先检查部门是否选择
                        // if (!warehouse.value.manageOrgId) {
                        //     ElMessage.warning('请先选择库管部门');
                        //     return;
                        // }

                        // managerDialogTitle.value = '选择仓库主管';
                        isLoadingManagers.value = true;

                        // 调用后端接口，获取指定部门的人员列表
                        const response = await axios.get('/BiWarehouse/GetWarehouseManagers', {
                            params: { manageOrgId: warehouse.value.manageOrgId }
                        });

                        if (response.data.code === 200) {
                            allManagers.value = response.data.data.map(item => ({
                                userId: item.UserId?.toString() || '',
                                userName: item.UsersName || '',
                                deptName: item.deptName || '仓储部',
                                phone: item.UsersHoneUmber || ''
                            }));
                            filteredManagers.value = [...allManagers.value];
                            managerDialogVisible.value = true;
                        }
                    } catch (error) {
                        ElMessage.error('获取人员列表失败：' + error.message);
                    } finally {
                        isLoadingManagers.value = false;
                    }
                };

                // 生成库位编号
                const generateLocationCode = async () => {
                    try {
                        const ruleId = 21;
                        const response = await axios.post('/NumberingRules/GenerateAndUpdateNumber', null, {
                            params: { ruleId }
                        });
                        if (response.data.success) {
                            return response.data.number;
                        } else {
                            ElMessage.warning('编号生成失败：' + response.data.message);
                            return null;
                        }
                    } catch (error) {
                        ElMessage.error('生成编号异常：' + error.message);
                        return null;
                    }
                };

                // 生成仓库编号
                const generateWarehouseCode = async () => {
                    try {
                        const ruleId = 22;
                        const response = await axios.post('/NumberingRules/GenerateAndUpdateNumber', null, {
                            params: { ruleId }
                        });
                        if (response.data.success) {
                            return response.data.number;
                        } else {
                            ElMessage.warning('编号生成失败：' + response.data.message);
                            return null;
                        }
                    } catch (error) {
                        ElMessage.error('生成编号异常：' + error.message);
                        return null;
                    }
                };

                // 新增库位
                const openAddLocationDialog = async () => {
                    if (!warehouse.value.warehouseCode) {
                        ElMessage.warning('仓库编号未生成，请刷新页面');
                        return;
                    }
                    const newCode = await generateLocationCode();
                    if (!newCode) {
                        return;
                    }
                    newLocationForm.value = {
                        storageLocationCode: newCode,
                        storageLocationName: '',
                        storageLocationCapacity: '',
                        managerId: '',
                        managerName: '',
                        storageLocationStatus: '1',
                        sortOrder: '',
                        remarks: ''
                    };
                    addDrawerVisible.value = true;
                };

                // 保存新增库位（先暂存到页面）
                const saveNewLocation = async () => {
                    if (!newLocationForm.value.storageLocationName) {
                        ElMessage.warning('库位名称不能为空');
                        return;
                    }
                    if (!newLocationForm.value.storageLocationCapacity) {
                        ElMessage.warning('库位容量不能为空');
                        return;
                    }

                    // 暂存到页面
                    const newLocation = { ...newLocationForm.value };
                    tempLocationList.value.push(newLocation);

                    // 更新分页显示
                    updatePagedLocationList();

                    ElMessage.success('库位已暂存');
                    addDrawerVisible.value = false;
                };

                // 编辑库位
                const openEditLocationDialog = (row) => {
                    currentLocation.value = { ...row };
                    locationDialogTitle.value = '编辑库位';
                    locationDialogVisible.value = true;
                };

                // 保存编辑库位
                const saveLocation = async () => {
                    if (!currentLocation.value.storageLocationCode || !currentLocation.value.storageLocationName) {
                        ElMessage.warning('编号和名称不能为空');
                        return;
                    }

                    // 更新暂存数据
                    const index = tempLocationList.value.findIndex(
                        item => item.storageLocationCode === currentLocation.value.storageLocationCode
                    );
                    if (index !== -1) {
                        tempLocationList.value.splice(index, 1, { ...currentLocation.value });
                        updatePagedLocationList();
                        ElMessage.success('编辑成功');
                        locationDialogVisible.value = false;
                    }
                };

                // 单个删除
                const deleteLocation = async (row) => {
                    ElMessageBox.confirm('确定删除该库位？', '确认删除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // 从暂存列表中删除
                        const index = tempLocationList.value.findIndex(
                            item => item.storageLocationCode === row.storageLocationCode
                        );
                        if (index !== -1) {
                            tempLocationList.value.splice(index, 1);
                            updatePagedLocationList();
                            ElMessage.success('删除成功');
                        }
                    });
                };

                // 批量删除
                const batchDeleteLocation = async () => {
                    if (selectedLocations.value.length === 0) {
                        ElMessage.warning('请选择需要删除的库位');
                        return;
                    }

                    ElMessageBox.confirm(`确定删除选中的 ${selectedLocations.value.length} 个库位？`, '确认删除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // 获取选中项的编号
                        const selectedCodes = selectedLocations.value.map(item => item.storageLocationCode);
                        // 过滤掉选中的项
                        tempLocationList.value = tempLocationList.value.filter(
                            item => !selectedCodes.includes(item.storageLocationCode)
                        );
                        // 清空选择
                        selectedLocations.value = [];
                        if (multipleTable.value) {
                            multipleTable.value.clearSelection();
                        }
                        // 更新分页
                        updatePagedLocationList();
                        ElMessage.success('批量删除成功');
                    });
                };

                // 库管部门选择
                const openOrgSelect = async () => {
                    try {
                        const response = await axios.get('/orgs/list');
                        if (response.data.code === 200) {
                            const orgs = response.data.data;
                            if (orgs.length > 0) {
                                warehouse.value.manageOrgName = orgs[0]?.org_name || '';
                                warehouse.value.manageOrgId = orgs[0]?.org_id || '';
                            } else {
                                ElMessage.warning('未找到任何部门数据');
                            }
                        } else {
                            ElMessage.error('获取部门列表失败: ' + (response.data.msg || '未知错误'));
                        }
                    } catch (error) {
                        ElMessage.error('获取部门列表失败：' + error.message);
                    }
                };

                // 导入导出
                const importLocation = () => {
                    ElMessage.info('导入功能开发中');
                };

                const exportLocation = async () => {
                    try {
                        const response = await axios.get('/location/export', { responseType: 'blob' });
                        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = '库位信息.xlsx';
                        a.click();
                        URL.revokeObjectURL(url);
                    } catch (error) {
                        ElMessage.error('导出失败：' + error.message);
                    }
                };

                // 仓库信息保存
                const closePage = () => {
                    window.history.back();
                };

                // 保存并新增
                const saveAndAdd = async () => {
                    // 使用事务同时保存仓库和库位
                    const result = await saveWithTransaction();
                    if (result) {
                        // 重置表单，准备新增
                        resetWarehouseForm();
                        ElMessage.success('保存成功，可继续新增');
                    }
                };

                // 保存数据（不刷新页面）
                const saveData = async () => {
                    const result = await saveWithTransaction();
                    if (result) {
                        isWarehouseSaved.value = true;
                        ElMessage.success('保存成功');
                    }
                };

                // 事务保存仓库和库位
                const saveWithTransaction = async () => {
                    // 校验仓库必填项
                    if (!warehouse.value.warehouseName) {
                        ElMessage.warning('请填写仓库名称');
                        return false;
                    }

                    try {
                        loading.value = true;
                        // 准备提交的数据
                        const submitData = {
                            warehouse: warehouse.value,
                            locations: tempLocationList.value
                        };

                        // 调用后端事务接口
                        const response = await axios.post('/BiWarehouse/SaveWithTransaction', submitData);
                        if (response.data.code === 200) {
                            return true;
                        } else {
                            ElMessage.warning('保存失败：' + response.data.msg);
                            return false;
                        }
                    } catch (error) {
                        ElMessage.error('保存异常：' + error.message);
                        return false;
                    } finally {
                        loading.value = false;
                    }
                };

                // 重置仓库表单
                const resetWarehouseForm = async () => {
                    // 生成新的仓库编号
                    const newCode = await generateWarehouseCode();

                    // 重置表单
                    warehouse.value = {
                        warehouseId: '',
                        warehouseCode: newCode || '',
                        isDefaultWarehouse: false,
                        warehouseName: '',
                        warehouseCapacity: '',
                        warehouseAddress: '',
                        manageOrgId: '',
                        manageOrgName: '',
                        managerId: '',
                        managerName: '',
                        UsersHoneUmber: '',
                        sortOrder: '',
                        warehouseStatus: '启用',
                        warehouseLocked: 'N',
                        remarks: ''
                    };

                    // 清空库位列表
                    tempLocationList.value = [];
                    updatePagedLocationList();
                    isWarehouseSaved.value = false;
                };

                return {
                    warehouse,
                    locationList,
                    selectedLocations,
                    locationDialogVisible,
                    locationDialogTitle,
                    currentLocation,
                    addDrawerVisible,
                    newLocationForm,
                    currentPage,
                    pageSize,
                    total,
                    pagedLocationList,
                    searchKeyword,
                    loading,
                    multipleTable,
                    isWarehouseSaved,
                    handleStatusChange,
                    handleSelectionChange,
                    handleSizeChange,
                    handleCurrentChange,
                    updatePagedLocationList,
                    openAddLocationDialog,
                    saveNewLocation,
                    openEditLocationDialog,
                    saveLocation,
                    deleteLocation,
                    batchDeleteLocation,
                    openLocationManagerSelect,
                    openNewLocationManagerSelect,
                    importLocation,
                    exportLocation,
                    closePage,
                    saveAndAdd,
                    saveData,
                    openOrgSelect,
                    openManagerSelect,
                    managerDialogVisible,
                    managerDialogTitle,
                    managerSearchKeyword,
                    filteredManagers,
                    selectManager,
                    confirmManagerSelection,
                    groupedManagers,
                    filterManagers,
                    isLoadingManagers,
                    deptList,
                    selectedManager
                };
            }
        }).use(ElementPlus, { locale: ElementPlusLocaleZhCn }).mount('#app');
    </script>
</body>
</html>